#include "MatAlgorithm.h"

#include "..\gui\feedframehandler.h"
#include "..\gui\gangiafeeddialog.h"


MatAlgorithm::MatAlgorithm():Algorithm()
{
	OpenMatlab();
}

MatAlgorithm::~MatAlgorithm(void)
{

}

void MatAlgorithm::Close(void)
{
	Algorithm::Close();
	if(pMatlab == NULL) return;

	pMatlab->Close();

	delete pMatlab;
	pMatlab = NULL;
	CoUninitialize();
}

void MatAlgorithm::OpenMatlab(void)
{	
	HRESULT		Res = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	while(Res != S_OK)
	{
		CoUninitialize();
		Res = CoInitializeEx(NULL,COINIT_MULTITHREADED);
	}
	pMatlab = new CMatlabEng();
	MatError = pMatlab->Open(NULL);
	if (MatError != -1)
	{
		pMatlab->SetVisible(TRUE);
		pMatlab->OutputBuffer(Output,1000);

		hinstLib = LoadLibrary(_("libmx.dll"));
		if (hinstLib != NULL)
		{
			pmxGetData		= (hmxGetData)		GetProcAddress(hinstLib, "mxGetData");
			pmxIsDouble		= (hmxIsDouble)		GetProcAddress(hinstLib, "mxIsDouble");
			pmxIsSingle		= (hmxIsSingle)		GetProcAddress(hinstLib, "mxIsSingle");
			pmxGetScalar	= (hmxGetScalar)	GetProcAddress(hinstLib, "mxGetScalar");
			pmxSetPr		= (hmxSetPr)		GetProcAddress(hinstLib, "mxSetPr");
			pmxGetPr		= (hmxGetPr)		GetProcAddress(hinstLib, "mxGetPr");
			pmxFree			= (hmxFree)			GetProcAddress(hinstLib, "mxFree");
			pmxCreateNumericMatrix		= (hmxCreateNumericMatrix)			GetProcAddress(hinstLib, "mxCreateNumericMatrix");
		}	
	}
}

void	MatAlgorithm::EvalString(wxString Command,bool EnableOutput)
{
	if(pMatlab == NULL)	
	{
		wxMessageBox(_("Matlab not initialized: please call MatAlgorithm::OpenMatlab()"),_("Error"));
		return;
	}

	memset(Output,0,sizeof(Output));
	pMatlab->EvalString(Command.ToAscii());
	
	if(EnableOutput && strlen(Output)>0)
	{
		wxMessageBox(wxString::Format(_("Matlab returned the following message: %s \r\n"),wxString::FromAscii(Output)));
	}
}
bool	MatAlgorithm::GetFromMatlab(char *VarName,c4mMatrix *pBlock)
{
	if(pMatlab == NULL)	
	{
		wxMessageBox(_("Matlab not initialized: please call MatAlgorithm::OpenMatlab()"),_("Error"));
		return false;
	}

	TempVect = pMatlab->GetVariable(VarName);
	if(TempVect == NULL)
	{
		wxMessageBox(wxString::Format(_("Variable %s doesn't exists in matlab workspace"),wxString::FromAscii(VarName)));
		return false;
	}
	memcpy(pBlock->pdata, (void *)pmxGetData(TempVect), sizeof(float)*pBlock->rows*pBlock->cols);
	return true;
}

void	MatAlgorithm::PutIntoMatlab(char *VarName,c4mMatrix *pBlock)
{
	if(pMatlab == NULL)	
	{
		wxMessageBox(_("Matlab not initialized: please call MatAlgorithm::OpenMatlab()"),_("Error"));
		return;
	}
	TempVect	=	pmxCreateNumericMatrix(pBlock->rows,pBlock->cols ,mxSINGLE_CLASS,mxREAL);
	memcpy((void *)pmxGetPr(TempVect), pBlock->pdata, sizeof(float)*pBlock->rows*pBlock->cols);
	pMatlab->PutVariable(VarName,TempVect);	
	//pmxFree(TempVect);
}

